package com.uni.taggroupview;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import androidx.annotation.NonNull;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.flexbox.JustifyContent;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class TagView extends FlexboxLayout {
    private String datas;
    private List<String> mTexts;
    private int bgColor;
    private int textColor;
    private int roundedCorners;  // 圆角具体值，只有isRounded为false才会生效
    private boolean isRounded;   // 是否圆角
    private boolean isHollowOut; // 是否镂空
    private int sideMode;        // 模式 普通 大
    private int styleMode;       // 0 默认没有左侧图标或文字 1 左侧显示一个字符 2 左侧显示图标
    private float textSize = 0;
    private int padd_top = 0;
    private int padd_left = 0;
    private int margin_right = 0;
    private int margin_bottom = 0;

    private int iconModeWidth= 0;
    private int iconModeHeight= 0;
    private int iconWidth= 0;
    private int iconHeght= 0;


    private int[] tagLeftBgColor;  // 标签左侧背景色，单个颜色即显示一种，多个颜色显示为横向渐变
    private int[] tagRightBgColor; // 标签右侧背景色，单个颜色即显示一种，多个颜色显示为横向渐变

    private int tagLeftIcon=0;

    private Context mContext;

    private Callback callback;
    private LongClickCallback longClickCallback;


    public TagView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.TagView);
        datas = mTypedArray.getString(R.styleable.TagView_textList);
        roundedCorners = mTypedArray.getInteger(R.styleable.TagView_roundedCorners, 5);
        if (datas != null && datas.indexOf(",") != -1) {
            mTexts = Arrays.asList(datas.split(","));
        }
        bgColor = mTypedArray.getColor(R.styleable.TagView_bgColor, 0);
        textColor = mTypedArray.getColor(R.styleable.TagView_textColor, Color.WHITE);
        isRounded = mTypedArray.getBoolean(R.styleable.TagView_isRounded, false);
        isHollowOut = mTypedArray.getBoolean(R.styleable.TagView_isHollowOut, false);
        sideMode = mTypedArray.getInt(R.styleable.TagView_sizeMode, 1);
        int mg_right = mTypedArray.getColor(R.styleable.TagView_marginRight, 10);
        int mg_bottom = mTypedArray.getColor(R.styleable.TagView_marginBottom, 5);
        styleMode = mTypedArray.getInt(R.styleable.TagView_styleMode, 0);
        margin_right = dip2px(mg_right);
        margin_bottom = dip2px(mg_bottom);
        String leftBgColors=mTypedArray.getString(R.styleable.TagView_leftBgColor);
        if (leftBgColors != null) {
            if(leftBgColors.indexOf(",") != -1){
                String[] sp1=leftBgColors.split(",");
                if(sp1[0]!=null && sp1[0].length()>0 && sp1[1]!=null && sp1[1].length()>0)
                tagLeftBgColor = new int[]{Color.parseColor(sp1[0]), Color.parseColor(sp1[1])};
            }else{
                tagLeftBgColor = new int[]{Color.parseColor(leftBgColors)};
            }
        }
        String rightBgColors=mTypedArray.getString(R.styleable.TagView_rightBgColor);
        if (rightBgColors != null) {
            if(rightBgColors.indexOf(",") != -1){
                String[] sp1=rightBgColors.split(",");
                if(sp1[0]!=null && sp1[0].length()>0 && sp1[1]!=null && sp1[1].length()>0)
                    tagRightBgColor = new int[]{Color.parseColor(sp1[0]), Color.parseColor(sp1[1])};
            }else{
                tagRightBgColor = new int[]{Color.parseColor(rightBgColors)};
            }
        }
        init();
    }

    private void init() {
        if (mTexts != null) setDatas(mTexts);
        this.setFlexDirection(FlexDirection.ROW);
        this.setJustifyContent(JustifyContent.FLEX_START);
        this.setFlexWrap(FlexWrap.WRAP);
    }

    public void setDatas(List<String> texts) {
        if (texts == null || texts.size() == 0) {
            throw new RuntimeException("请设置需要显示的内容，字符需要逗号隔开");
        }

        this.mTexts = texts;
        this.removeAllViews();
        initSizeMode();
        showList(texts);
        this.invalidate();
    }

    private void showList(List<String> texts) {
        if (styleMode == 0) {
            for (int i = 0; i < texts.size(); i++) {
                View view = makeTextView(mTexts.get(i));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(0, margin_bottom, margin_right, 0);
                int finalI = i;
                view.setOnClickListener(v -> {
                    if (callback != null) callback.onClick(view, finalI);
                });
                view.setOnLongClickListener(v -> {
                    if (longClickCallback != null) {
                        longClickCallback.onLongClick(v, finalI);
                        return true;
                    } else {
                        return false;
                    }
                });
                this.addView(view, layoutParams);
            }
        } else {
            for (int i = 0; i < texts.size(); i++) {
                View view = makeIconView(mTexts.get(i),i);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(0, margin_bottom, margin_right, 0);
                int finalI = i;
                view.setOnClickListener(v -> {
                    if (callback != null) callback.onClick(view, finalI);
                });
                view.setOnLongClickListener(v -> {
                    if (longClickCallback != null) {
                        longClickCallback.onLongClick(v, finalI);
                        return true;
                    } else {
                        return false;
                    }
                });
                this.addView(view, layoutParams);
            }
        }

    }

    // 绘制圆角描边的TextView
    private TextView makeTextView(String s) {
        TextView textView = new TextView(mContext);
        textView.setText(s);
        textView.setTextSize(textSize);
        int randomColor = 0;
        if (bgColor == 0) {
            Random random = new Random();
            randomColor = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
        } else {
            randomColor = bgColor;
        }

        if (!isHollowOut) {
            textView.setTextColor(textColor);
        } else {
            textView.setTextColor(randomColor);
        }
        textView.setPadding(padd_left, padd_top, padd_left, padd_top);
        int rounded = isRounded ? 1000 : roundedCorners;
        textView.setBackground(getBgDrawable(rounded, randomColor, isHollowOut));
        return textView;
    }

    // 绘制圆角描边的TextView
    private View makeIconView(String s,int i) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.tag_icon_text, null);
        LinearLayout fl_left_top = view.findViewById(R.id.fl_left_top);
        TextView tv_left_text = view.findViewById(R.id.tv_left_text);
        ImageView iv_icon = view.findViewById(R.id.iv_icon);
        LinearLayout lly_right_down = view.findViewById(R.id.lly_right_down);
        TextView textView_right = view.findViewById(R.id.textView_right);
        if (styleMode == 1) {
            tv_left_text.setVisibility(VISIBLE);
            iv_icon.setVisibility(GONE);
            tv_left_text.setText(s.substring(0,1));
            tv_left_text.setTextSize(textSize);
        } else {
            tv_left_text.setVisibility(GONE);
            iv_icon.setVisibility(VISIBLE);
        }
        if(tagLeftIcon!=0){
            iv_icon.setImageResource(tagLeftIcon);
        }else{
            iv_icon.setImageResource(R.mipmap.ic_wujiaoxing);
        }

        textView_right.setText(s);
        textView_right.setTextSize(textSize);
        // pading
        LinearLayout.LayoutParams left_top = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        left_top.width=iconModeWidth;
        left_top.height=iconModeHeight;
        fl_left_top.setLayoutParams(left_top);

        LinearLayout.LayoutParams right_down = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        right_down.height=iconModeWidth;
        lly_right_down.setLayoutParams(right_down);

        LinearLayout.LayoutParams icon = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        icon.width=iconWidth;
        icon.height=iconHeght;
        iv_icon.setLayoutParams(icon);
        // 圆角颜色
        if(tagLeftBgColor!=null)
            fl_left_top.setBackground(getGradient(tagLeftBgColor,RaiduType.TOP_LEFT_BOTTOM,roundedCorners));
        if(tagRightBgColor!=null)
            lly_right_down.setBackground(getGradient(tagRightBgColor,RaiduType.TOP_RIGHT_BOTTOM,roundedCorners));

        return view;
    }

    public void removeIteByIndex(int position) {
        if (this.mTexts == null || this.mTexts.size() == 0) return;
        if (position > -1 && position < this.mTexts.size()) {
            this.mTexts.remove(position);
            this.removeViewAt(position);
        }
    }

    public void removeAll() {
        if (this.mTexts == null) return;
        this.mTexts.clear();
        this.removeAllViews();
    }

    private void initSizeMode() {
        switch (sideMode) {
            case SizeMode.SMALL:
                textSize = 10f;
                padd_top = dip2px(3);
                padd_left = dip2px(5);
                iconModeWidth=dip2px(20);
                iconModeHeight=dip2px(20);
                iconWidth= (int) (iconModeWidth/(float)1.5);
                iconHeght=(int) (iconModeHeight/(float)1.5);
                break;
            case SizeMode.LARGE:
                textSize = 16f;
                padd_top = dip2px(5);
                padd_left = dip2px(12);
                iconModeWidth=dip2px(30);
                iconModeHeight=dip2px(30);
                iconWidth= (int) (iconModeWidth/(float)1.5);
                iconHeght=(int) (iconModeHeight/(float)1.5);
                break;
            case SizeMode.GENERAL:
            default:
                textSize = 14f;
                padd_top = dip2px(4);
                padd_left = dip2px(8);
                iconModeWidth=dip2px(25);
                iconModeHeight=dip2px(25);
                iconWidth= (int) (iconModeWidth/(float)1.5);
                iconHeght=(int) (iconModeHeight/(float)1.5);
                break;
        }
    }


    /**
     * 生成圆角背景
     *
     * @param rd        圆角大小
     * @param bgColor   背景颜色,如果不设置则为随机颜色
     * @param hollowOut 是否镂空
     * @return
     */
    public GradientDrawable getBgDrawable(int rd, int bgColor, boolean hollowOut) {
//        Log.e("TAG", "rd: "+rd);
        int radius = dip2px(rd); // 转化为dp
        GradientDrawable drawable = new GradientDrawable();
        drawable.setCornerRadius(radius);
        if (!hollowOut) drawable.setColor(bgColor);
        else drawable.setStroke(2, bgColor);
        return drawable;
    }

    public GradientDrawable getGradient(int[] color, RaiduType radiutype, int rd) {
        GradientDrawable drawable=null;
        if(color.length<2){
            drawable=new GradientDrawable();
            drawable.setColor(color[0]);
        }else {
            drawable= new GradientDrawable(GradientDrawable.Orientation.BL_TR, color);
        }
        // 设置圆角
        int radius = dip2px(rd); // 转化为dp
        float[] newRadius = getRadiutype(radiutype, radius);
        drawable.setCornerRadii(newRadius);
        return drawable;
    }

    private float[] getRadiutype(RaiduType radiutype, int radius) {
        float[] newRadius = new float[8];
        int[] tlb = {0, 1, 6, 7}; // 0,1为左上角  6，7为左下角
        int[] trb = {2, 3, 4, 5};
        switch (radiutype) {
            case TOP_LEFT_BOTTOM: // 左上角、 左下角 设置圆角
                for (int i : tlb) newRadius[i] = radius;
                break;
            case TOP_RIGHT_BOTTOM:
                for (int i : trb) newRadius[i] = radius;
                break;
        }
        return newRadius;
    }


    public int dip2px(float dipValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public int getStyleMode() {
        return styleMode;
    }

    public void setStyleMode(int styleMode) {
        this.styleMode = styleMode;
    }

    public enum RaiduType {
        TOP_LEFT_BOTTOM,
        TOP_RIGHT_BOTTOM,
    }

    public void refresh() {
        setDatas(mTexts);
    }


    public void setClickCallback(Callback mCallback) {
        this.callback = mCallback;
    }

    public void setLongClickCallback(LongClickCallback mCallback) {
        this.longClickCallback = mCallback;
    }

    public interface Callback {
        void onClick(View v, int index);
    }

    public interface LongClickCallback {
        boolean onLongClick(View view, int index);
    }

    public int getBgColor() {
        return bgColor;
    }

    public void setBgColor(int bgColor) {
        this.bgColor = bgColor;
    }

    public int getTextColor() {
        return textColor;
    }

    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    public int getRoundedCorners() {
        return roundedCorners;
    }

    public void setRoundedCorners(int roundedCorners) {
        this.roundedCorners = roundedCorners;
    }

    public boolean isRounded() {
        return isRounded;
    }

    public void setRounded(boolean rounded) {
        isRounded = rounded;
    }

    public boolean isHollowOut() {
        return isHollowOut;
    }

    public void setHollowOut(boolean hollowOut) {
        isHollowOut = hollowOut;
    }

    public int getSideMode() {
        return sideMode;
    }

    public void setSideMode(int sideMode) {
        this.sideMode = sideMode;
    }

    public int getIconModeWidth() {
        return iconModeWidth;
    }

    public void setIconModeWidth(int iconModeWidth) {
        this.iconModeWidth = iconModeWidth;
    }

    public int getIconModeHeight() {
        return iconModeHeight;
    }

    public void setIconModeHeight(int iconModeHeight) {
        this.iconModeHeight = iconModeHeight;
    }

    public int getIconWidth() {
        return iconWidth;
    }

    public void setIconWidth(int iconWidth) {
        this.iconWidth = iconWidth;
    }

    public int getIconHeght() {
        return iconHeght;
    }

    public void setIconHeght(int iconHeght) {
        this.iconHeght = iconHeght;
    }

    public String getDatas() {
        return datas;
    }

    public void setDatas(String datas) {
        this.datas = datas;
    }

    public int[] getTagLeftBgColor() {
        return tagLeftBgColor;
    }

    public void setTagLeftBgColor(int[] tagLeftBgColor) {
        this.tagLeftBgColor = tagLeftBgColor;
    }

    public int[] getTagRightBgColor() {
        return tagRightBgColor;
    }

    public void setTagRightBgColor(int[] tagRightBgColor) {
        this.tagRightBgColor = tagRightBgColor;
    }

    public int getTagLeftIcon() {
        return tagLeftIcon;
    }

    public void setTagLeftIcon(int tagLeftIcon) {
        this.tagLeftIcon = tagLeftIcon;
    }

    public interface SizeMode {
        int SMALL = 0;
        int GENERAL = 1;
        int LARGE = 2;
    }
}
